<template>
  <div class="generation-header">
    <h3>代码生成（Code Generation）</h3>
  </div>
  <n-divider/>
  <!-- 搜索条件 -->
  <n-form ref="formRef" inline :label-width="80" :model="formValue" label-placement="left"
          label-width="auto" require-mark-placement="right-hanging">
    <n-form-item label="表名称" path="tableName">
      <n-input v-model:value="formValue.tableName" placeholder="输入表名称"  @keyup.enter="handleValidateClick"/>
    </n-form-item>
    <n-form-item>
      <n-space>
        <n-button attr-type="button" type="info" @click="handleValidateClick">
          搜索
        </n-button>
        <n-button attr-type="button" @click="handleResetValidate">
          重置
        </n-button>
      </n-space>
    </n-form-item>
  </n-form>
  <!-- 操作按钮 -->
  <n-space>
    <n-button type="info" @click="handleImportClick">
      导入
    </n-button>
  </n-space>
  <!-- 表单 -->
  <n-data-table
      :columns="columns"
      :data="tableData"
      :pagination="pagination"
      :bordered="false"
      :loading="tableLoading"
  />

  <!-- 导入 -->
  <codeGenerationImport
      v-model:show="customEditShow"
      @handleSubmit="handleCusSubmit"
  ></codeGenerationImport>
  <!-- 编辑 -->
  <codeGenerationEditor v-model:show="customEditRowShow" :tableName="tableName"></codeGenerationEditor>

  <!-- 下载 -->
  <n-modal v-model:show="showDownloadModal" preset="dialog" style="width: 400px;" title="生成并下载代码"
           :mask-closable="false" :close-on-esc="false">
    <n-form ref="formDownloadRef" :label-width="80" :model="formDownloadValue" label-placement="left">
      <n-form-item label="业务" path="business">
        <n-input v-model:value="formDownloadValue.business" placeholder="输入业务"/>
      </n-form-item>
      <n-form-item label="忽略前缀" path="ignorePrefix">
        <n-input v-model:value="formDownloadValue.ignorePrefix" placeholder="输入忽略前缀"/>
      </n-form-item>
      <n-form-item label="表名" path="tableName">
        <n-input v-model:value="formDownloadValue.tableName" disabled placeholder="输入表名"/>
      </n-form-item>
      <n-form-item label="类型" path="type">
        <n-radio-group v-model:value="formDownloadValue.type">
          <n-space>
            <n-radio :value="1">
              带流程
            </n-radio>
            <n-radio :value="2">
              不带流程
            </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <div style="display: flex; justify-content: flex-end;">
        <n-space>
          <n-button type="info" attr-type="button" @click="handleDownloadClick">
            下载
          </n-button>
          <n-button attr-type="button" @click="handleResetDownload">
            取消
          </n-button>
        </n-space>

      </div>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import {ref, h, reactive} from 'vue';
import type {FormInst, DataTableColumns} from 'naive-ui'
import {NButton, NSpace} from 'naive-ui'
import codeGenerationImport from './codeGenerationImport.vue'
import codeGenerationEditor from './codeGenerationEditor.vue'
import {getXXTableListAPI, downloadFileAPI, exportExcel} from '@/api/api'

const tableName = ref<string | null>(null)
const formRef = ref<FormInst | null>(null)
const formDownloadRef = ref<FormInst | null>(null)
const showDownloadModal = ref(false) as Boolean; // 下载弹窗

const formValue = ref({
  tableName: ''
})

const formDownloadValue = ref({
  tableName: '',
  business: '',
  ignorePrefix: 'pdm_',
  type: 1,
  downloadName: ''
})

const handleValidateClick = (e: MouseEvent) => {
  e.preventDefault()
  getTableData()
}
const handleResetValidate = () => {
  formValue.value.tableName = '';
  getTableData()
}

// 表格数据
const tableLoading = ref(false) as Boolean;
const customEditRowShow = ref(false) as Boolean;
const pagination = reactive({
  page: 1,
  itemCount: 0,
  pageSize: 10,
  showSizePicker: true,
  prefix: () => {
    return `共 ${pagination.itemCount} 条`
  },
  pageSizes: [
    {
      label: '10 每页',
      value: 10
    },
    {
      label: '20 每页',
      value: 20
    },
    {
      label: '50 每页',
      value: 50
    },
    {
      label: '100 每页',
      value: 100
    }
  ],
  onUpdatePage: (page: number) => {
    pagination.page = page
  },
  onUpdatePageSize: (size: null | number) => {
    console.log(size, pagination)
    pagination.pageSize = size
  }
});

interface Song {
  id: string
  title: string
  tablename: string
  tableidentity: string
}

function createColumns({play}: { play: (row: Song, type: string) => void }): DataTableColumns<Song> {
  return [
    {
      title: '序号',
      key: 'index',
      width: 60,
      align: 'center',
      render: (_, index) => {
        return `${(pagination.page - 1) * pagination.pageSize + index + 1}`
      }
    },
    {
      title: '表名称',
      key: 'tablename'
    },
    {
      title: '表描述',
      key: 'title'
    },
    {
      title: 'tableidentity',
      key: 'tableidentity'
    },
    {
      title: '操作',
      key: 'action',
      width: 230,
      render(row) {
        const viewBtn = [
          h(NButton, {
            strong: true,
            tertiary: true,
            size: 'small',
            type: 'info',
            onClick: () => play(row, 'editor')
          }, {
            default: () => '编辑'
          }),
          h(NButton, {
            strong: true,
            tertiary: true,
            size: 'small',
            onClick: () => play(row, 'download')
          }, {
            default: () => '生成并下载代码'
          })
        ]
        return h(NSpace, {}, {
          default: () => viewBtn
        })
      }
    }
  ]
}

const columns = createColumns({
  play: (row, type) => {
    console.log(row, type)
    switch (type) {
      case 'editor':
        tableName.value = row?.tablename || ''
        customEditRowShow.value = true
        break;
      case 'download':
        showDownloadModal.value = true
        formDownloadValue.value.tableName = row?.tablename || ''
        formDownloadValue.value.downloadName = row?.title || ''
        break;
      default:
        break;
    }
  }
});
const tableData = ref<Song[]>([])

const getTableData = async (params: any) => {
  tableLoading.value = true
  const res = await getXXTableListAPI({
    tableName: formValue.value?.tableName || ''
  })
  console.log(res)
  if (res.status === 200) {
    tableData.value = res.value?.data || []
    pagination.itemCount = res.value?.rows || 0
  }
  tableLoading.value = false
}
getTableData()

const handleCusSubmit = () => {
  getTableData()
}

// 导入弹窗
const customEditShow = ref(false) as Boolean
const handleImportClick = () => {
  customEditShow.value = true
}

// 下载弹窗
const handleDownloadClick = (e: MouseEvent) => {
  e.preventDefault()
  formDownloadRef.value?.validate(async (errors) => {
    if (!errors) {
      const res = await downloadFileAPI({
        ...formDownloadValue.value,
      })
      console.log(res)
      await exportExcel(res, `${formDownloadValue.value.downloadName}`, 'zip')
      showDownloadModal.value = false
    } else {
      window.$message.error('请检查输入项')
    }
  })
}
const handleResetDownload = () => {
  const {formRef} = formDownloadRef.value
  formRef?.restoreValidation()
  showDownloadModal.value = false
}
</script>

<style scoped lang="scss">

</style>